using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System.Reflection;
using System.Net;


namespace revoStore
{
partial class MainWindow
{
    string currentapp = null;


    #region System Menu code
    [DllImport("user32.dll")]
    private static extern int GetSystemMenu(IntPtr hwnd, int bRevert);

    [DllImport("user32.dll")]
    private static extern int AppendMenu(
      int hMenu, int Flagsw, int IDNewItem, string lpNewItem);

    [DllImport("user32.dll")]
    private static extern bool InsertMenu(IntPtr hMenu,
    Int32 wPosition, Int32 wFlags, Int32 wIDNewItem,
    string lpNewItem);

    [DllImport("user32.dll")]
    static extern bool DrawMenuBar(IntPtr hWnd);

    public const Int32 WM_SYSCOMMAND = 0x112;
    public const Int32 MF_SEPARATOR = 0x800;
    public const Int32 MF_BYPOSITION = 0x400;
    public const Int32 MF_STRING = 0x0;
    public const Int32 IDM_EDITFUNDS = 1000;
    public const Int32 IDM_ANALYZE = 1001;

    private void SetupSystemMenu()
    {
        // get handle to system menu
        int menu = GetSystemMenu(this.Handle, 0);

        AppendMenu(menu, MF_SEPARATOR, 0, string.Empty);
        AppendMenu(menu, MF_STRING, 1234, "Store");
        AppendMenu(menu, MF_STRING, 1235, "My Apps");
        AppendMenu(menu, MF_STRING, 1236, "Settings");
        DrawMenuBar(this.Handle);

        /*InsertMenu(menu, 5, 0, 1234, "Store");
        InsertMenu(menu, 6, 0, 1235, "My Apps");
        InsertMenu(menu, 7, 0, 1236, "Settings");*/
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        // WM_SYSCOMMAND is 0x112
        if (m.Msg == 0x112)
        {
            // check for my new menu item ID
            if (m.WParam.ToInt32() == 1234)
            {
                ChangeTab(tbStore);
            }
            else if (m.WParam.ToInt32() == 1235)
            {
                ChangeTab(tbMyApps);
            }
            else if (m.WParam.ToInt32() == 1236)
            {
                ChangeTab(tbSett);
            }
        }
    }
    #endregion


    private void ChangeTab(object sender, EventArgs e)
	{
		if (((Button)sender).Equals(btnStore)) {
			btnStore.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(148)), Convert.ToInt32(Convert.ToByte(163)), Convert.ToInt32(Convert.ToByte(182)));
			btnMyApps.BackColor = System.Drawing.Color.Transparent;
			btnSett.BackColor = System.Drawing.Color.Transparent;
			tb.SelectedTab = tbStore;
		} else if (((Button)sender).Equals(btnMyApps)) {
			btnMyApps.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(148)), Convert.ToInt32(Convert.ToByte(163)), Convert.ToInt32(Convert.ToByte(182)));
			btnStore.BackColor = System.Drawing.Color.Transparent;
			btnSett.BackColor = System.Drawing.Color.Transparent;
            /*if (currentapp == null)
            {*/
                tb.SelectedTab = tbMyApps;
            /*}
            else
            {
                tb.SelectedTab = appPage;
            }*/
		} else if (((Button)sender).Equals(btnSett)) {
			btnSett.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(148)), Convert.ToInt32(Convert.ToByte(163)), Convert.ToInt32(Convert.ToByte(182)));
			btnMyApps.BackColor = System.Drawing.Color.Transparent;
			btnStore.BackColor = System.Drawing.Color.Transparent;
			tb.SelectedTab = tbSett;
		}
	}

    private void ChangeTab2(object sender, EventArgs e)
    {
        if (((Button)sender).Equals(btnStoreHome))
        {
            btnStoreHome.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(148)), Convert.ToInt32(Convert.ToByte(163)), Convert.ToInt32(Convert.ToByte(182)));
            btnStoreList.BackColor = System.Drawing.Color.Transparent;
            tbxStore.SelectedTab = tbStoreHome;
        }
        else if (((Button)sender).Equals(btnStoreList))
        {
            btnStoreList.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(148)), Convert.ToInt32(Convert.ToByte(163)), Convert.ToInt32(Convert.ToByte(182)));
            btnStoreHome.BackColor = System.Drawing.Color.Transparent;
            /*if (currentapp == null)
            {*/
            tbxStore.SelectedTab = tbStoreList;
            /*}
            else
            {
                tb.SelectedTab = appPage;
            }*/
        }
    }

    private void ChangeTab(TabPage t)
    {
        if (t.Equals(tbStore))
        {
            ChangeTab(btnStore, new EventArgs());
        }
        else if (t.Equals(tbMyApps))
        {
            ChangeTab(btnMyApps, new EventArgs());
        }
        else if (t.Equals(tbSett))
        {
            ChangeTab(btnSett, new EventArgs());
        }
    }

	private void RevoButton1_Click(object sender, EventArgs e)
	{
		if (ContextMenuStrip1.Visible) {
			ContextMenuStrip1.Close();
			ContextMenuStrip1.Visible = false;
		} else {
			ContextMenuStrip1.Visible = true;
			ContextMenuStrip1.Show(btnInst, new Point(0, btnInst.Location.Y + btnInst.Height));
		}
	}

	private void lkblLogin_LinkClicked(object sender, EventArgs e)
	{
		if (pnlLog.Visible) {
			pnlLog.Visible = false;
			pnlLog.Location = new Point(0, 0);
		} else {
			pnlLog.Location = new Point(KryptonPanel3.Location.X - 89, 35);
			pnlLog.Visible = true;
		}
	}

	private const int WM_SETCURSOR = 0x20;

	private const int IDC_HAND = 32649;
	[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
	private static extern IntPtr LoadCursor(IntPtr hInstance, int lpCursorName);

	[DllImport("user32.dll", CharSet = CharSet.Auto)]
	private static extern IntPtr SetCursor(IntPtr hCursor);

    private void MainWindow_Load_OneTime(object sender, EventArgs e)
    {
        this.btnRefresh.Image = global::revoStore.Properties.Resources.refresh1;

        this.pctAvatar.BackgroundImage = global::revoStore.Properties.Resources.usrframe;
        this.pctAvatar.Image = global::revoStore.Properties.Resources.defaultavatar;

        this.pnlLog.BackgroundImage = global::revoStore.Properties.Resources.tooltip1;

        this.btnBack.Image = global::revoStore.Properties.Resources.back1;

        this.btnNext.Image = global::revoStore.Properties.Resources.next1;

        this.btnRefresh.Image = global::revoStore.Properties.Resources.refresh1;
         // System Menu code
        SetupSystemMenu();

        /*ListViewItem it = new ListViewItem();
        App g = new App(@"Example files\firefox.xml", false);

        it.Text = g.Name;
        it.SubItems.Add(g.Version);
        it.SubItems.Add(g.Creator);
        it.SubItems.Add("Ready");
        lstMyApps.Items.Add(it);*/

        /*ListViewItem it2 = new ListViewItem();
        Package p = new Package(@"Example files\firefox.rpkg");
     

        it2.Text = p.Application.Name + "_from a package ;)";
        it2.SubItems.Add(p.Application.Version);
        it2.SubItems.Add(p.Application.Creator);
        it2.SubItems.Add("Ready");
        lstMyApps.Items.Add(it2);*/
        //LoadPackage(@"Example files\firefox.rpkg");


        //revoStore.Properties.Settings.Default.OfficialRepositories = new System.Collections.Specialized.StringCollection();
        //revoStore.Properties.Settings.Default.Repositories = new System.Collections.Specialized.StringCollection();
        //revoStore.Properties.Settings.Default.Apps = new System.Collections.Specialized.StringCollection();


        foreach (string s in revoStore.Properties.Settings.Default.OfficialRepositories)
        {
            //MessageBox.Show(s);
            txOffRepos.Text += s;
            txOffRepos.Text += Environment.NewLine;
        }

        foreach (string s in revoStore.Properties.Settings.Default.Repositories)
        {
            //MessageBox.Show(s);
            txRepos.Text += s;
            txRepos.Text += Environment.NewLine;
        }


        foreach (string s in revoStore.Properties.Settings.Default.Apps)
        {
            //MessageBox.Show(s);
            LoadPackage(s, false);
        }
    }

	private void MainWindow_Load(object sender, EventArgs e)
	{
       


		if (!chkRem.Checked) {
			txUser.Text = "";
			txPass.Text = "";
		}
		pctAvatar.BringToFront();
		btnInst.BringToFront();
		//pctAvatar.SendToBack()
		//Dim it As New ListViewItem
        
	}

	private void lkblLogin_MouseEnter(object sender, EventArgs e)
	{
		this.lkblLogin.Font = new System.Drawing.Font("Segoe UI", 9f, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
	}

	private void lkblLogin_MouseLeave(object sender, EventArgs e)
	{
		this.lkblLogin.Font = new System.Drawing.Font("Segoe UI", 9f, FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
	}


	private void PictureBox1_Click(object sender, EventArgs e)
	{
	}

	private void MainWindow_SizeChanged(object sender, EventArgs e)
	{
		if (!pnlLog.Visible) {
		//pnlLog.Visible = False
		//pnlLog.Location = New Point(0, 0)
		} else {
			pnlLog.Location = new Point(KryptonPanel3.Location.X - 89, 34);
			//pnlLog.Visible = True
		}
	}

    private void KryptonPanel4_Paint(object sender, PaintEventArgs e)
    {

    }

    private void lstMyApps_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void FromRevoStorePackageToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
        {
            if (!openFileDialog1.FileName.EndsWith(".rpkg"))
            {
                MessageBox.Show("Error: Not a package file! Check the file extension");
                return;
            }
            else
            {
                LoadPackage(openFileDialog1.FileName);
            }
        }
    }

ListViewItem it2 = new ListViewItem();

public void LoadPackage(string pkgFile, bool install = true)
{
    LoadPackage2(pkgFile, install);

    if (install)
    {
  
        revoStore.Properties.Settings.Default.Apps.Add(pkgFile);       
    }
}

    public void LoadPackage2(string pkgFile, bool install = true)
    {
        it2 = new ListViewItem();
        Package p = new Package(pkgFile, install);


        it2.Text = p.Application.Name;
        it2.SubItems.Add(p.Application.Version);
        it2.SubItems.Add(p.Application.Creator);
        if (!p.Download)
        {
            if (install)
            {
                it2.SubItems.Add("Installing...");
                p.runInst();
            }
            else
            {
                it2.SubItems.Add("Ready");
            }
            it2.SubItems.Add(pkgFile);
            lstMyApps.Items.Add(it2);


            p.Installed += PackageInstalled;
            p.p.Exited += PackageInstalled;
        }
        else
        {
            if (install)
            {
                it2.SubItems.Add("Downloading...");
  p.webClient.DownloadProgressChanged += ProgressChanged;
                p.runInst();
              
            }
            else
            {
                it2.SubItems.Add("Ready");
                //return;
            }
            it2.SubItems.Add(pkgFile);
            lstMyApps.Items.Add(it2);

            //p.webClient.DownloadProgressChanged += ProgressChanged;

            p.Installed += PackageInstalled;
            p.p.Exited += PackageInstalled;
        }
    }

    public void Setup_Downloaded(object sender, EventArgs e)
    {
        this.SetText("Installing...");
    }

    public void PackageInstalled(object sender, EventArgs e)
    {
        this.SetText("Ready");
        //MessageBox.Show("ready");
    }

    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        //label1.Text = Convert.ToString(bytesIn);

        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); //stays at -1
        //label2.Text = Convert.ToString(totalBytes);

        double percentage = bytesIn / totalBytes * 100;
        //label3.Text = Convert.ToString(percentage);
        this.SetText("Downloading... " + int.Parse(Math.Truncate(percentage).ToString()) + "%");
        //progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
    }

    public void g()
    {
lstMyApps.Items[lstMyApps.Items.IndexOf(it2)].SubItems[3].Text = "Ready";
    }
    delegate void SetTextCallback(string text);
    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.lstMyApps.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.lstMyApps.Items[lstMyApps.Items.IndexOf(it2)].SubItems[3].Text = text;
        }
    }


    private void contextMenuStrip2_Opening(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (lstMyApps.SelectedItems.Count == 0)
        {
            setMode("nothing");
        }
        else
        {
            setMode("app");
        }
    }

    public void setMode(string md)
    {
        if (md == "app")
        {
            openToolStripMenuItem.Visible = true;
            showToolStripMenuItem.Visible = true;
            toolStripSeparator1.Visible = true;
            uninstallToolStripMenuItem.Visible = true;
            installAnAppFromAPackageToolStripMenuItem.Visible = false;
        }
        else if (md == "nothing")
        {
            openToolStripMenuItem.Visible = false;
            showToolStripMenuItem.Visible = false;
            toolStripSeparator1.Visible = false;
            uninstallToolStripMenuItem.Visible = false;
            installAnAppFromAPackageToolStripMenuItem.Visible = true;
        }
    }

    private void showToolStripMenuItem_Click(object sender, EventArgs e)
    {
        lblAppTitle.Text = lstMyApps.SelectedItems[0].Text;
        lblAppVersion.Text = lstMyApps.SelectedItems[0].SubItems[1].Text;
        lblAppDev.Text = lstMyApps.SelectedItems[0].SubItems[2].Text;
        //lblAppVersion.Text = lstMyApps.SelectedItems[0].SubItems[0].Text;
        Package p = new Package(lstMyApps.SelectedItems[0].SubItems[4].Text, false);
        lblAppType.Text = p.Application.Type;
        this.tb.SelectedTab = appPage;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        /*global::revoStore.Properties.Settings.Default.OfficialRepositories = new List<string>();
        global::revoStore.Properties.Settings.Default.OfficialRepositories.Add("http://revostore.tk/repo/");
        global::revoStore.Properties.Settings.Default.OfficialRepositories.Add("http://dl.gruntxproductions.net/repo/");*/
       // global::revoStore.Properties.Settings.Default.ggg.Add("g");
    }

    private void btnSettApply_Click(object sender, EventArgs e)
    {
        abc:
        try
        {
revoStore.Properties.Settings.Default.Repositories.Clear();
        }
        catch (Exception)
        {
            revoStore.Properties.Settings.Default.Repositories = new System.Collections.Specialized.StringCollection();
            goto abc;
        }        
        foreach (string repo in txRepos.Lines)
        {
            revoStore.Properties.Settings.Default.Repositories.Add(repo);
        }
    }

    private void btnLog_Click(object sender, EventArgs e)
    {
        if (Users.UserServer.LogIn(txUser.Text, txPass.Text))
        {
            MessageBox.Show("yes");
        }
        else
        {
            MessageBox.Show("no");
        }
    }
	
}
}